package com.xinyue.gateway.server.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.xinyue.utils.NettyUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
@Service
@Scope(scopeName = "prototype")
public class GameHeartbeatHandler extends ChannelInboundHandlerAdapter {
    private Logger logger = LoggerFactory.getLogger(GameIdleStateHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            String ip = NettyUtil.getIp(ctx);
            String channelId = ctx.channel().id().asShortText();
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state() == IdleState.READER_IDLE) {
                logger.debug("ip {} channel {} 空闲，关闭连接", ip, channelId);
                ctx.close();
            } else if (idleStateEvent.state() == IdleState.WRITER_IDLE) {
                logger.warn("ip {} channel {} 长时间无逻辑消息回复，关闭连接");
            }
        }
        ctx.fireUserEventTriggered(evt);

    }
}
